import os.path
from os.path import exists
import yaml

class YamlHelper:
    def __init__(self):
        self._data: dict = {}
        self._path = ''
        self.is_new_yaml = False

    def read(self, path):
        if not exists(path):
            # print('yaml is not exist.')
            self.is_new_yaml = True
        else:
            with open(path, 'r', encoding='utf-8') as f:
                self._data = yaml.safe_load(f)
        self._path = path
        return self._data

    def write(self, path=None):
        if path is None:
            path = self._path
        d = os.path.dirname(path)
        if not os.path.exists(d):
            os.makedirs(d)
        with open(path, 'w', encoding='utf-8') as f:
            yaml.safe_dump(self._data, f)

    @staticmethod
    def _handle_key_type(key):
        return list(map(str, key))

    def set(self, *key, value):
        tmp = self._data
        i = self._handle_key_type(key)
        for j in i[:-1]:
            if tmp.get(j) is None:
                tmp[j] = {}
            tmp = tmp.get(j)
        tmp[i[-1]] = value

    def get(self, *key, get_type=str):
        tmp: dict = self._data
        i = self._handle_key_type(key)
        for j in i:
            if tmp.get(j) is None:
                return None
            tmp = tmp.get(j)
        r = get_type(tmp)
        return r